package br.com.requisicao.compra.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.requisicao.compra.canonico.Fornecedor;
import br.com.requisicao.compra.dao.IFornecedorDAO;
import br.com.requisicao.compra.util.HibernateUtil;


public class FornecedorDAO implements IFornecedorDAO {

	public void salvar(Fornecedor fornecedor) {
		Session session = HibernateUtil.getSession();
		try {
			Transaction tx = session.beginTransaction();
			session.saveOrUpdate(fornecedor);
			tx.commit();
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public Fornecedor pesquisarPorId(Long codigo) {
		Session session = HibernateUtil.getSession();
		Fornecedor fornecedor = null;
		try {
			fornecedor = (Fornecedor) session.get(Fornecedor.class, codigo);
		} finally {
			session.close();
		}

		return fornecedor;
	}

	public List<Fornecedor> obtermFornecedor() {
		Session session = HibernateUtil.getSession();
		List<Fornecedor> fornecedor = null;
		try {

			fornecedor = session.createCriteria(Fornecedor.class)
					.addOrder(Order.asc("fornecedor")).list();
		} finally {
			session.close();
		}

		return fornecedor;
	}

	public Fornecedor excluir(Fornecedor fornecedor) {
		Session session = HibernateUtil.getSession();
		try {

			Transaction tx = session.beginTransaction();
			session.delete(fornecedor);
			tx.commit();
			session.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Fornecedor obtemFornecedorPorId(Long codigo) {
		Session session = HibernateUtil.getSession();
		Fornecedor fornecedor = null;
		try {

			fornecedor = (Fornecedor) session.createCriteria(Fornecedor.class).
					add(Restrictions.eq("cidade.codigo", codigo)).uniqueResult();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return fornecedor;
	}
}
